﻿using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;

namespace HttpProxy
{
    class Proxy
    {
       
        private readonly SslStream _sslStream;

        private readonly byte[] _read = new byte[1024 * 1024];

        private readonly Encoding _ascii = Encoding.ASCII;

        //设定编码
        private readonly Byte[] _recvBytes = new Byte[4096];
        //定义一个空间，存储Web服务器返回的数据

        private string contentType = "text/html; charset=utf-8";

        public Proxy(SslStream sslStream)
        {
            _sslStream = sslStream;
        }

        public void Run()
        {
  
            string clientMessage = ReadMessage(_sslStream);

            var urlMatch = Regex.Match(clientMessage, "[POST|GET]\\s([^\\s]*?)\\sHTTP/[1\\.1|1\\.2]");
            var url = urlMatch.Groups[1].Value;
         
            
            
//            SendMessage(_clientSocket, statusline);
//            SendMessage(_clientSocket, header);
//            SendMessage(_clientSocket, "\r\n");
//            SendMessage(_clientSocket, html);
//            _clientSocket.Close();
        }

        //接收客户端的HTTP请求数据
        private string ReadMessage(SslStream sslStream)
        {
            
            StringBuilder messageData = new StringBuilder();
            int readLen = -1;
            do
            {
                readLen = sslStream.Read(_read, 0, _read.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(_read, 0, readLen)];
                decoder.GetChars(_read, 0, readLen, chars, 0);
                messageData.Append(chars);
            } while (readLen != 0);

            return messageData.ToString();
        }
        
        //传送从Web服务器反馈的数据到客户端
        private void SendMessage(SslStream sslStream, string message)
        {
            var bytes = Encoding.UTF8.GetBytes(message);
            _sslStream.Write(bytes);
            _sslStream.Flush();
        }

        private string PostUrl(string url, string postData)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072; // SecurityProtocolType.Tls1.2; 
                request.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
            }
            else
            {
                request = (HttpWebRequest) WebRequest.Create(url);
            }

            request.Method = "POST"; //使用get方式发送数据
            HandleHeader(request);

            byte[] data = Encoding.UTF8.GetBytes(postData);
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            //获取网页响应结果
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();

            HandleResponseHeader(response);
            Stream stream = response.GetResponseStream();
            string result = string.Empty;
            using (StreamReader sr = new StreamReader(stream))
            {
                result = sr.ReadToEnd();
            }

            return result;
        }

        private string Get(string url)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072; // SecurityProtocolType.Tls1.2; 
                request.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
            }
            else
            {
                request = (HttpWebRequest) WebRequest.Create(url);
            }

            request.Method = "GET"; //使用get方式发送数据
            HandleHeader(request);

            //获取网页响应结果
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            HandleResponseHeader(response);
            Stream stream = response.GetResponseStream();
            //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string result = string.Empty;
            using (StreamReader sr = new StreamReader(stream))
            {
                result = sr.ReadToEnd();
            }

            return result;
        }

        private void HandleHeader(HttpWebRequest request)
        {
            request.ContentType = contentType;
            request.Referer = null;
            request.AllowAutoRedirect = true;
            request.UserAgent =
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.Accept = "*/*";
        }

        private static void HandleResponseHeader(HttpWebResponse response)
        {
            
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

    }
}